package com.fy.servlet;

import java.sql.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import com.fy.util.DbUtil;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) {
		String username = request.getParameter("username"); // 获取用户名
		String passwrod = request.getParameter("password"); // 获取密码
		Connection conn = null; // 定义connection 负责数据库程序和数据库之间的联系
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from users where loginname=? and password=?";
		try {
			conn = DbUtil.getMyConn(); // 获取连接
			ps = conn.prepareStatement(sql); // 预执行静态的sql语句
			ps.setString(1, username);
			ps.setString(2, passwrod);
			rs = ps.executeQuery(); // 执行并返回它所生成的结果
			if (rs.next())
				response.sendRedirect("index.to"); // 如果用户名跟密码正确重定向到首页
			else
				request.getRequestDispatcher("/WEB-INF/page/error.jsp").forward(request, response); // 如果用户名跟密码不正确则重定向到错误页面
		} catch (Exception e) {
			e.printStackTrace(); // 打印异常
		} finally {
			DbUtil.close(conn, ps, rs); // 关闭连接
		}
	}
}